package com.currency.mall.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.event.MainEvent;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.login.LoginActivity;
import com.currency.mall.ui.main.MainActivity;
import com.currency.mall.util.MD5Util;
import com.currency.mall.util.PwdCheckUtil;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.commonbusines.entity.ResponseBean;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/25.
 */

public class UpdatePwdActivity extends BaseActivity {

    @BindView(R.id.et_input_old_pwd)
    EditText etInputOldPwd;
    @BindView(R.id.iv_old_pwd)
    ImageView ivOldPwd;
    @BindView(R.id.rl_old_pwd)
    RelativeLayout rlOldPwd;
    @BindView(R.id.et_input_pwd)
    EditText etInputPwd;
    @BindView(R.id.iv_pwd)
    ImageView ivPwd;
    @BindView(R.id.rl_pwd)
    RelativeLayout rlPwd;
    @BindView(R.id.et_confirm_pwd)
    EditText etConfirmPwd;
    @BindView(R.id.iv_confirm_pwd)
    ImageView ivConfirmPwd;
    @BindView(R.id.rl_et_confirm_pwd)
    RelativeLayout rlEtConfirmPwd;
    @BindView(R.id.ll_set_pwd)
    LinearLayout llSetPwd;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    private boolean oldPwdDisplayFlg = false;
    private boolean pwdDisplayFlg = false;
    private boolean confirmPwdDisplayFlg = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_pwd);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(getContext(), R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    private void init(){
        etInputOldPwd.addTextChangedListener(pwdTextWatcher);
        etInputPwd.addTextChangedListener(pwdTextWatcher);
        etConfirmPwd.addTextChangedListener(pwdTextWatcher);

    }

    TextWatcher pwdTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String oldPwd = etInputOldPwd.getText().toString().trim();
            String pwd = etConfirmPwd.getText().toString().trim();
            String confirmPwd = etConfirmPwd.getText().toString().trim();
            if (TextUtils.isEmpty(oldPwd) || TextUtils.isEmpty(pwd) || TextUtils.isEmpty(confirmPwd)|| TextUtils.isEmpty(s)) {
                btnSubmit.setBackgroundResource(R.drawable.btn_bg);
                btnSubmit.getBackground().setAlpha(50);
                btnSubmit.setClickable(false);
            } else {
                btnSubmit.setBackgroundResource(R.drawable.btn_bg);
                btnSubmit.getBackground().setAlpha(250);
                btnSubmit.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    public void updatePwd() {
        String pwd = etInputOldPwd.getText().toString().trim();
        String confirmPwd = etConfirmPwd.getText().toString().trim();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("passwd",  MD5Util.toMD5(pwd).toLowerCase());
        hashMap.put("newPasswd",  MD5Util.toMD5(confirmPwd).toLowerCase());
        showLoading();
        NetWork.getLoginApi().updatePwd(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        hideLoading();
                    }

                    @Override
                    public void onNext(ResponseBean responseBean) {
                        hideLoading();
                        if (responseBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            ToastUitl.show("修改密码成功，请重新登录", 200);
                            PreferenceUtils.clearLoginInfo();
                            startActivity(new Intent(getContext(), MainActivity.class));
                            EventBus.getDefault().post(new MainEvent(MainEvent.HOME_LOGIN));
                            finish();
                        } else if (responseBean.getCode().equals("9112")) {
                            toLogin();
                        } else {
                            ToastUitl.show(responseBean.getMsg(), 200);
                        }

                    }
                });
    }

    private boolean  etVerification(){
        String  strPwd = etInputPwd.getText().toString();
        String  strConfirmPwd = etConfirmPwd.getText().toString();
        if(strPwd.length()<8){
            ToastUitl.show("密码长度是8到32",200);
            return false;
        }else if(strConfirmPwd.length()<8){
            ToastUitl.show("密码长度是8到32",200);
            return false;
        }else if(!strPwd.equals(strConfirmPwd)){
            ToastUitl.show("两次输入的密码不一致",200);
            return false;
        }else if(!PwdCheckUtil.isPasswordInfo(strPwd)){
            ToastUitl.show("密码须包含数字、字母、符号至少2种或以上元素",200);
            return false;
        }else if(!PwdCheckUtil.isPasswordInfo(strConfirmPwd)){
            ToastUitl.show("密码须包含数字、字母、符号至少2种或以上元素",200);
            return false;
        }
        return  true;

    }

    private void oldPwdTransformation() {

        if (!oldPwdDisplayFlg) {
            // display password text, for example "123456"
            etInputOldPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etInputOldPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        oldPwdDisplayFlg = !oldPwdDisplayFlg;

        etInputOldPwd.postInvalidate();

        if (oldPwdDisplayFlg) {
            ivOldPwd.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            ivOldPwd.setImageResource(R.drawable.yanjing_guanbi);
        }
        etInputOldPwd.setSelection(etInputOldPwd.getText().toString().length());
    }

    private void pwdTransformation() {

        if (!pwdDisplayFlg) {
            // display password text, for example "123456"
            etInputPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etInputPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        pwdDisplayFlg = !pwdDisplayFlg;

        etInputPwd.postInvalidate();

        if (pwdDisplayFlg) {
            ivPwd.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            ivPwd.setImageResource(R.drawable.yanjing_guanbi);
        }
        etInputPwd.setSelection(etInputPwd.getText().toString().length());
    }

    private void confirmPwdTransformation() {

        if (!confirmPwdDisplayFlg) {
            // display password text, for example "123456"
            etConfirmPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etConfirmPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        confirmPwdDisplayFlg = !confirmPwdDisplayFlg;

        etConfirmPwd.postInvalidate();

        if (confirmPwdDisplayFlg) {
            ivConfirmPwd.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            ivConfirmPwd.setImageResource(R.drawable.yanjing_guanbi);
        }
        etConfirmPwd.setSelection(etConfirmPwd.getText().toString().length());
    }


    public void toLogin() {
        startActivity(new Intent(getContext(), LoginActivity.class));
    }


    @OnClick({R.id.ll_back, R.id.iv_old_pwd, R.id.rl_old_pwd, R.id.iv_pwd, R.id.rl_pwd, R.id.iv_confirm_pwd, R.id.rl_et_confirm_pwd, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_old_pwd:
                oldPwdTransformation();
                break;
            case R.id.rl_old_pwd:
                break;
            case R.id.iv_pwd:
                pwdTransformation();
                break;
            case R.id.rl_pwd:
                break;
            case R.id.iv_confirm_pwd:
                confirmPwdTransformation();
                break;
            case R.id.rl_et_confirm_pwd:
                break;
            case R.id.btn_submit:
                if(etVerification()){
                    updatePwd();
                }
                break;
        }
    }
}
